package com.exp.bookhouse.aspect;

import com.exp.bookhouse.util.DateUtil;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.Date;

//使用切面对小程序端访问接口进行日志处理，写到log文件中
@Aspect
@Component
public class BookAspect {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Pointcut("execution(* com.exp.bookhouse.controller.*.*(..))")
    public void log(){}

    @Before("log()")
    public void doBefore(JoinPoint joinPoint){
        //获取request对象
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();

        String url = request.getRequestURL().toString();
        String ip = request.getRemoteAddr();
        String classMethod = joinPoint.getSignature().getDeclaringTypeName()+"."+joinPoint.getSignature().getName();
        Object[] args = joinPoint.getArgs();
        String date = DateUtil.formatTimesTampDate(new Date());

        RequestLog requestLog = new RequestLog(url, ip, classMethod, args, date);
        logger.info("requestLog: {}",requestLog);
    }

    @After("log()")
    public void doAfter(){}

    @AfterReturning(pointcut = "log()",returning = "result")
    public void doAfterReturning(Object result){
        logger.info("result: {}",result);
    }

    //日志类
    private class RequestLog{
        String url;     //请求url
        String ip;      //ip地址
        String classMethod;     //class + method
        Object[] args;      //方法的参数
        String date;        //时间

        public RequestLog(String url, String ip, String classMethod, Object[] args, String date) {
            this.url = url;
            this.ip = ip;
            this.classMethod = classMethod;
            this.args = args;
            this.date = date;
        }

        @Override
        public String toString() {
            return "RequestLog{" +
                    "url='" + url + '\'' +
                    ", ip='" + ip + '\'' +
                    ", classMethod='" + classMethod + '\'' +
                    ", args=" + Arrays.toString(args) +
                    ", date='" + date + '\'' +
                    '}';
        }
    }

}
